<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */

namespace app\service\notice\email;

use app\enum\NoticeEnum;
use app\service\BaseService;
use app\service\notice\NoticeInterface;
use app\service\notice\NoticeLogTrait;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

final class EmailService extends BaseService implements NoticeInterface
{
    use NoticeLogTrait;

    /**
     * @var array 请求参数
     */
    protected array $req = [];

    /**
     * @var array 应答参数
     */
    protected array $rep = [];

    /**
     * @var array 接收人
     */
    protected array $staffs = [];

    /**
     * @var int 通知类型
     */
    protected int $noticeType = NoticeEnum::NOTICE_TYPE_EMAIL;

    private PHPMailer $mail;

    /**
     * @throws Exception
     */
    public function __construct()
    {
        $this->mail = new PHPMailer(true);
        $this->mail->isSMTP(); // Send using SMTP
        $this->mail->CharSet = 'UTF-8'; // 编码格式为UTF-8，不设置编码的话，中文会出现乱码
        $this->mail->Host = 'smtp.exmail.qq.com'; // Set the SMTP server to send through
        $this->mail->SMTPAuth = true; // Enable SMTP authentication
        $this->mail->Username = 'is@iseconds.cn'; // SMTP username
        $this->mail->Password = 'ABCabc2020#778'; // SMTP password
        $this->mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Enable implicit TLS encryption
        $this->mail->Port = 465; // TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
        $this->mail->setFrom('is@iseconds.cn', '哈勃智投');
    }

    /**
     * 批量发送消息.
     * @param array $to_emails emails
     * @param string $subject 标题
     * @param $content_body
     * @param array $attachments
     * @param array $cc_emails
     * @param array $bcc_emails
     * @return bool
     * @throws Exception
     */
    public function sendHtmlMail(array $to_emails, string $subject, $content_body, array $attachments = [], array $cc_emails = [], array $bcc_emails = []): bool
    {
        $this->rep = [
            'subject' => $subject,
            'content_body' => $content_body,
        ];
        $this->staffs = $to_emails;
        $this->setParameter($to_emails, $subject, $content_body, $attachments, $cc_emails, $bcc_emails);
        $this->mail->isHTML();
        $this->mail->send();
        if (! $this->setNoticeLog()) {
            return false;
        }
        return $this->isSendSuccess() || self::setError($res['msg'] ?? '发送失败');
    }

    /**
     * 单条发送消息.
     * @param array $params 请求参数
     * @return bool
     */
    public function sendSingleMessage(array $params = []): bool
    {
        return true;
    }

    /**
     * 批量发送消息.
     * @param array $params 请求参数
     * @return bool
     * @throws Exception
     */
    public function sendBatchMessage(array $params = []): bool
    {
        $this->req = $params;
        $this->setParameter($params['to_emails'], $params['subject'], $params['content_body'], $params['attachments'] ?? [], $params['cc_emails'] ?? [], $params['bcc_emails'] ?? []);
        $this->mail->isHTML();
        $this->mail->send();
        if (! $this->setNoticeLog()) {
            return false;
        }
        return $this->isSendSuccess() || self::setError($res['msg'] ?? '发送失败');
    }

    /**
     * 设置配置.
     * @param array $conf 配置
     * @return bool
     */
    public function setConf(array $conf = []): bool
    {
        return true;
    }

    /**
     * 获取参数.
     * @param array $params 请求参数
     * @return array
     */
    public function getParam(array $params = []): array
    {
        return $params;
    }

    /**
     * 是否发送成功.
     * @return bool
     */
    public function isSendSuccess(): bool
    {
        return true;
    }

    /**
     * 设置发送配置.
     * @param array $attachments
     * @param array $cc_emails
     * @param array $bcc_emails
     * @param mixed $to_emails emails
     * @param mixed $subject 标题
     * @param mixed $content_body
     * @throws Exception
     */
    private function setParameter($to_emails, $subject, $content_body, array $attachments = [], array $cc_emails = [], array $bcc_emails = [])
    {
        // 收件人
        foreach ($to_emails as $email) {
            $this->mail->addAddress($email, $email);
        }

        // 抄送
        if (! empty($cc_emails)) {
            foreach ($cc_emails as $email) {
                $this->mail->addCC($email);
            }
        }

        // 密送
        if (! empty($bcc_emails)) {
            foreach ($bcc_emails as $email) {
                $this->mail->addBCC($email);
            }
        }

        if (! empty($attachments)) {
            foreach ($attachments as $attachment) {
                $this->mail->addAttachment($attachment);
            }
        }

        $this->mail->Subject = $subject;
        $this->mail->Body = $content_body;
        $this->mail->AltBody = strip_tags($content_body);
    }
}
